<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
    <style>
        body {
            margin: 0;
        }
        .box {
            width: 100px;
            height: 100px;
            background: red;
            transform: translate(100px, 100px);
        }
    </style>
</head>
<body>
    <div class="box"></div>

    <script>

        // 按住ctrl拖动
        const box = document.querySelector('.box');
        let innerX = 0;
        let innerY = 0;
        // ctrl键是否被按下
        let isCtrlDown = false;

        document.addEventListener('contextmenu', function (e) {
            e.preventDefault();
        });

        document.addEventListener('keydown', function (e) {
            if (e.keyCode === 17) {
                isCtrlDown = true;
            }
        });

        document.addEventListener('keyup', function (e) {
            if (e.keyCode === 17) {
                isCtrlDown = false;
            }
        });

        // 鼠标滑动事件函数
        function onMouseMove (e) {
            if (!isCtrlDown) {
                return;
            }
            const x = e.pageX;
            const y = e.pageY;
            box.setAttribute('style', `transform: translate(${ x - innerX }px, ${ y - innerY }px);`);
        }

        // 鼠标按下
        box.addEventListener('mousedown', function (e) {
            // 阻止默认行为
            e.preventDefault();
            // 记录鼠标相对小盒子的位置
            innerX = e.offsetX;
            innerY = e.offsetY;
            // 鼠标按下绑定滑动事件
            document.addEventListener('mousemove', onMouseMove);
        });

        // 鼠标抬起时解绑滑动事件
        // 鼠标移出屏幕时 不能触发box的鼠标抬起事件
        // 所以mouseup应该绑定在document上 才能正确移除onMouseMove事件函数
        document.addEventListener('mouseup', function () {
            document.removeEventListener('mousemove', onMouseMove);
        });


    </script>
</body>
</html>